<template>
  <md-popup v-model="show" position="bottom">
    <md-popup-title-bar only-close :title="$t('box.buy')" :describe="$t('box.describe')" title-align="left" @cancel="show = false" />
    <div style="background: #fff; padding: 20px">
      <md-input-item type="digit" v-model="num" align="center" is-highlight>
        <template #right>≈&nbsp;<md-amount :value="Number(amount)" :precision="2" transition></md-amount>&nbsp;HWD</template>
      </md-input-item>
      <div style="padding-top: 20px">
        <md-button type="primary" @click="action" round>{{ $t('confirm') }}</md-button>
      </div>
    </div>
  </md-popup>
</template>

<script setup>
import { ref, watch } from 'vue'
import { asset } from '@/api/box'
import { toast } from '@/style'
import { t } from '@/lang'
import { formWei } from '@/web3';
import { pay, query, address } from '@/web3/contracts/buy';
import { allowance as usdtAllowance, approve as usdtApprove } from '@/web3/contracts/usdt';
import { allowance, approve } from '@/web3/contracts/hwd';

const emit= defineEmits(['load', 'over'])
const show = ref(false)
const num = ref(0)
const amount = ref('')

const open = (data) => {
  show.value = true
  num.value = 1
}

const action = async () => {
  if(num.value > 0) {
    if(Number(await allowance(address)) == 0) {
      // 授权
      toast(t('contracts.hwd.approve'), 'ring', 0)
      try{
        await approve(address)
      } catch(e) {
        return toast(false)
      }
    }
    if(Number(await usdtAllowance(address)) == 0) {
      // 授权
      toast(t('contracts.usdt.approve'), 'ring', 0)
      try{
        await usdtApprove(address)
      } catch(e) {
        return toast(false)
      }
    }
    // 开始转入
    show.value = false
    emit('load')
    pay(num.value).then(() => {
      emit('over')
    }).catch((err) => {
      toast(t('box.error'))
    })
  }
}

watch(num, () => {
  if(!num.value) return
  query(num.value).then(res => {
    amount.value = formWei(res)
  })
})

defineExpose({ open })

</script>